<?php

$this->useClass("Handler_Community");
class Action_Community_RssSubscriptions extends Handler_Community
{
	private $lib_rss;
	
	public function init() {
		parent::init();
		$this->rh->UseClass("RL_URLGenerator");
		$this->rh->UseClass("RSSAggregator_RssLibWrapper");
		$this->lib_rss = new RssLibWrapper();
	}
	
	public function process ()
	{
		$aa = $this->aa;
		$acl_data = $aa->getInfo();
		if (!$aa->is_granted('community_edit')) return;
	
		$model = $this->ctx->mm->getModel("RssFeedList", "m");
		$model->setCommunityOid($acl_data['comity_oid']);
		
		// добавление подписки
		if (isset($this->rh->GET['url']) && (!empty($this->rh->GET['url']))) {
			$url = $this->rh->GET['url'];
			$new_feed_added = 0;
			if ($this->lib_rss->isRss($url)) {
				$rss = 	$this->lib_rss->fetch($url);
				
				switch ($model->addFeed($url, $rss)) {
					case 0:
					$new_feed_added = 1;
					break;
					
					case 1:
					$error = 1; // ошибка при сохранении в бд
					break;
					
					case 2:
					$error = 2; // дубликат
				}
			} else {
				$error = 3; // фид не является rss лентой
				}
		}

		// удаление подписки
		if (isset($this->rh->GET['delete_oid']) && (!empty($this->rh->GET['delete_oid']))) {
			$delete_oid = $this->rh->GET['delete_oid'];
			$delete_success = 0;
			if ($model->rmFeed( $delete_oid )) {
				$delete_success = 1;
				}
		}

		
		$view = $this->rh->views->findByName('rss_subscriptions');
		$view->data = $aa->template_data;
		$subscrs = $model->getFeedList();
		
		foreach ($subscrs as $k=>$subscr) {
				$ug = new RL_URLGenerator($this->rh->router->getRule("rss_manage")); //
				$ug->setRouter($this->rh->router);
				$ug->setParams($this->params);
				$ug->setGet(array("delete_oid"=>$subscr['oid']));
				$subscrs[$k]['delete_url'] = $ug->generateUrl();

			}
		
		$view->data['rss_subscriptions'] = $subscrs;
		$view->data['new_feed_added'] = $new_feed_added;
		$view->data['error'] = $error;
		$view->data['delete_success'] = $delete_success;
		
		$this->rh->response->setContent($view);

	} // end of function process

}

